<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="1010px" top="10vh" @close='close'>
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" label-width="100px" :rules="rules" class="blackForm" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="name" style="width:400px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc" ref="desc" style="width:400px;" :autosize="{ minRows: 4 }" size='small' type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
        </el-form-item>
        <div class="strategyFatherBox">
          <el-button type="success" size='small' @click="largeConfig(record)" class="largeConfig">{{$t('添加规则')}}</el-button>
        </div>
        <el-scrollbar style="margin-top:20px" class="blackScrollbar">
          <el-table ref="multipleTable" :data="record.rule_map" size='mini'>
            <el-table-column type="selection" align='center' width="55"></el-table-column>
            <el-table-column prop="rule_id" align='center' :label="$t('规则ID')" width="80" />
            <el-table-column prop="proto" align='center' :label="$t('协议/应用')">
              <template slot-scope="scope">
                <tooltip :copyText="scope.row.proto" class="wid190">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="match_option" align='center' :label="$t('匹配选项')" :formatter="matchOptionFormatter" />
            <el-table-column prop="match_direction" align='center' :label="$t('匹配方向')" :formatter="matchDirectionFormatter" />
            <el-table-column prop="content" align='center' :label="$t('关键字')">
              <template slot-scope="scope">
                {{ record.id ? scope.row.content.join(',') : scope.row.content }}
              </template>
            </el-table-column>
            <el-table-column prop="action" align='center' :label="$t('动作')" :formatter="actionFormatter" />
            <el-table-column align="center" :label="$t('操作')" fixed="right" width="100">
              <template slot-scope="scope">
                <el-button type="danger" plain @click="deleteRule(scope.row)" size='mini' :class="'del' + (scope.$index + 1)">{{$t('删除')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </el-form>
      <rule-dialog v-if="ruleDialogVisible" ref="refRuleDialogVisible" @listData='listData'></rule-dialog>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addBlacklist, editBlacklist, delBlackRule, getBlackInfo } from '@/api/safe/black'
import RuleDialog from './RuleDialog'
import { inputClass, texttextClass } from '@/utils/input-class.js'
export default {
  components: { RuleDialog },
  name: 'blackDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      ruleDialogVisible: false,
      record: {
        id: null,
        old_name: '',
        name: '',
        desc: '',
        rule_map: []
      },
      recordCopy: {
        id: null,
        old_name: '',
        name: '',
        desc: '',
        rule_map: []
      },
      protoOneList: ['http', 'ftp', 'smtp', 'pop3', 'imap', 'telnet'],
      protoList: {
        'http': {
          'download': this.$t('下载'),
          'upload': this.$t('上传')
        },
        'ftp': {
          'both': this.$t('所有'),
          'download': this.$t('下载'),
          'upload': this.$t('上传'),
          'cmd': this.$t('命令')
        },
        'smtp': {
          'All': this.$t('所有'),
          'From': this.$t('发件人'),
          'To': this.$t('收件人'),
          'Subject': this.$t('主题'),
          'Filename': this.$t('文件名'),
          'Body': this.$t('正文')
        },
        'pop3': {
          'All': this.$t('所有'),
          'From': this.$t('发件人'),
          'To': this.$t('收件人'),
          'Subject': this.$t('主题'),
          'Filename': this.$t('文件名'),
          'Body': this.$t('正文')
        },
        'imap': {
          'All': this.$t('所有'),
          'From': this.$t('发件人'),
          'To': this.$t('收件人'),
          'Subject': this.$t('主题'),
          'Filename': this.$t('文件名'),
          'Body': this.$t('正文')
        },
        'telnet': {
          'both': this.$t('所有'),
          'download': this.$t('服务器'),
          'upload': this.$t('客户端')
        }
      },
      typeList: { //   alert/deny  告警/阻断
        'alert': this.$t('告警'),
        'deny': this.$t('阻断')
      },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.desc': {
      handler (newVal) {
        if (newVal) {
          this.record.desc = newVal.replace(/[\r\n]/g, '')
        }
      },
      immediate: true
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data1 = ['name']
        const textdata = ['desc']
        inputClass(this.$refs, data1)
        texttextClass(this.$refs, textdata)
        if (data) {
          this.record.old_name = data.name
          this.record.name = data.name
          this.record.id = data.id
          this.record.desc = data.desc
          this.record.rule_map = data.rule_map
          // data.rule_map.forEach(row => {
          //   this.$refs.multipleTable.toggleRowSelection(row)
          // })
        }
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.record.rule_map && this.record.rule_map.length > 0) {
            var formData = Object.assign({}, this.record)
            formData.rule_map = JSON.stringify(formData.rule_map)
            if (this.record.id) {
              editBlacklist(formData).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              addBlacklist(formData).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            }
          } else {
            this.$message({
              message: this.$t('请至少选择一条数据进行添加'),
              type: 'error'
            })
          }
        }
      })
    },
    listData (data) {
      if (data) {
        this.record.rule_map.push(data)
        this.ruleIdChange()
      } else {
        getBlackInfo({ name: this.record.old_name }).then(res => {
          if (res.status === 0) {
            this.record.rule_map = res.info[0].rule_map
          }
        })
      }
    },
    // 重新分配规则id
    ruleIdChange () {
      this.record.rule_map.forEach((tab, index) => {
        tab.rule_id = index + 1
      })
    },
    // 批量配置按钮
    largeConfig (data) {
      this.ruleDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refRuleDialogVisible.init(data)
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.record.rule_map = []
      this.$refs.multipleTable.clearSelection()
      this.$refs.form.resetFields()
    },
    deleteRule (row) {
      this.$confirm(this.$t('您是否要删除所选中的规则？'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        confirmButtonClass: 'confirmButton',
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        if (this.record.id) {
          delBlackRule({ name: this.record.old_name, rule_id: row.rule_id }).then(res => {
            if (res.status === 0) {
              this.$message({
                message: this.$t(res.msg),
                type: 'success'
              })
              getBlackInfo({ name: this.record.old_name }).then(res => {
                this.record.rule_map = res.info[0].rule_map
                this.$parent.listData()
              })
            }
          })
        } else {
          this.record.rule_map.splice(row.rule_id - 1, 1)
          this.ruleIdChange()
        }
      })
    },
    matchOptionFormatter (val) {
      if (this.protoOneList.includes(val.proto)) {
        return this.protoList[val.proto][val.match_option] ? this.protoList[val.proto][val.match_option] : ''
      }
    },
    matchDirectionFormatter (val) {
      if (this.protoOneList.includes(val.proto)) {
        return this.protoList[val.proto][val.match_direction] ? this.protoList[val.proto][val.match_direction] : ''
      }
    },
    actionFormatter (val) {
      return this.typeList[val.action]
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
<style lang="less" scoped>
.blackScrollbar {
  position: relative;

  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
